//
//  ShopPayForViewController.m
//  HuiMWorld
//
//  Created by chirui on 2018/1/17.
//  Copyright © 2018年 Shui. All rights reserved.
//

#import "ShopPayForViewController.h"


@interface ShopPayForViewController (){
    
    NSString * pay_pwdStr;
    NSString * _payType;
}
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;
@property (weak, nonatomic) IBOutlet UIButton *wxBtn;
@property (weak, nonatomic) IBOutlet UIButton *zfbBtn;
@property (weak, nonatomic) IBOutlet UIButton *blanceBtn;
@property (weak, nonatomic) IBOutlet UIButton *xinyongBtn;
@property (weak, nonatomic) IBOutlet UIButton *sureBtn;
@property (weak, nonatomic) IBOutlet UIButton *addBtn;


@end

@implementation ShopPayForViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    TitleView(@"支付方式");
    _payType = @"wxpay";
    _wxBtn.selected = YES;
    
    //微信
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(payWxResultOpt:)
                                                 name: WX_NOTIFY_KEY
                                               object:nil];

    //支付宝
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(ZFBSuccess:)
                                                 name: @"zfb"
                                               object:nil];

    self.priceLabel.attributedText = [SHJudgeTools changeAllStr:[NSString stringWithFormat:@"￥%@",self.dataDic[@"order_price"]] partStr:@"￥" color:NavBackColor font:15];
    
   
    
    // 支付密码输入框
    self.verifyCodeInputView = [[VerifyCodeInputView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-SH_TopHeight)];
    self.verifyCodeInputView.inputView.delegate = self;
    [self.verifyCodeInputView setHidden:YES];
    [self.view addSubview:self.verifyCodeInputView];
   
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"icon_nav_renter" target:self action:@selector(backBtnClick)];
}

-(void)backBtnClick{
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)wxBtnClick:(id)sender {
      _payType = @"wxpay";
      _wxBtn.selected = YES;
      _zfbBtn.selected = NO;
      _blanceBtn.selected = NO;
      _xinyongBtn.selected = NO;
     _addBtn.selected = NO;
}

- (IBAction)zfuBtnClick:(id)sender {
    _payType = @"alipay";
    _wxBtn.selected = NO;
    _zfbBtn.selected = YES;
    _blanceBtn.selected = NO;
    _xinyongBtn.selected = NO;
    _addBtn.selected = NO;
}
- (IBAction)blanceClick:(id)sender {
    _payType = @"balance";
    _wxBtn.selected = NO;
    _zfbBtn.selected = NO;
    _blanceBtn.selected = YES;
    _xinyongBtn.selected = NO;
    _addBtn.selected = NO;
}
- (IBAction)xinyongBtnClick:(id)sender {
    _payType = @"score";
    _wxBtn.selected = NO;
    _zfbBtn.selected = NO;
    _blanceBtn.selected = NO;
    _xinyongBtn.selected = YES;
    _addBtn.selected = NO;
}
- (IBAction)sureBtnClick:(id)sender {
    

    if ([_payType isEqualToString:@"alipay"]||[_payType isEqualToString:@"wxpay"]) {
        
        [self topUpBanceRequest];
    }else{
        
         [self checkPayPasswordSetting];
    }

}
- (IBAction)addBtnClick:(UIButton *)sender {
    
    _payType = @"mixed";
    _wxBtn.selected = NO;
    _zfbBtn.selected = NO;
    _blanceBtn.selected = NO;
    _xinyongBtn.selected = NO;
    _addBtn.selected = YES;
}


- (void)checkPayPasswordSetting {
    

        [self.verifyCodeInputView setHidden:NO];
        [self.verifyCodeInputView.inputView.textFieldArray[0] becomeFirstResponder];
}

#pragma mark - 支付密码输入完成回调
- (void)inputFinishedWithText:(NSString *)text {
    // text为用户输入的6位密码

    [self.verifyCodeInputView resignFirstResponder];
    
    self.verifyCodeInputView.hidden = YES;
    pay_pwdStr = text;
    for(UITextField *textField in self.verifyCodeInputView.inputView.textFieldArray) {
        textField.text = @"";
    }
    
    if (pay_pwdStr.length!=6) {
        [SHJudgeTools MBProgressHUDPromptWith:@"支付密码格式不正确" On:self.view];
        return;
    }else {

        [self requestPayForNetFor:self.dataDic[@"order_id"]]; // 余额支付
    }
    
}


// 余额支付
-(void)requestPayForNetFor:(NSString *)order{
    
    NSString * parametersStr = [NSString stringWithFormat:@"%@%@",address_url,balance_payFor_api];

    NSDictionary * dic = @{@"pay_password":pay_pwdStr,
                           @"token":USER_DEFAULTGet(@"token"),
                           @"mid":USER_DEFAULTGet(@"mid"),
                           @"order_id":order,
                           @"pay_type":_payType
                           };

    [PostNetWorking postNetWorkingStr:parametersStr  andparameters:dic  Success:^(id responseObject) {

        if ([responseObject[@"code"] intValue]==200) {

            UIAlertView *alerte = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"支付成功了~~！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alerte show];

        } else {

            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }

    } failed:^(NSError *error) {

        NSLog(@"ERROR ==%@",error);
        SHuiMBhudTextNetError;
    }];
}

-(void)topUpBanceRequest {
    
    
    NSDictionary * dic = @{@"mid":USER_DEFAULTGet(@"mid"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"order_id":self.dataDic[@"order_id"],
                           @"pay_type":_payType
                           };
    SHuiMBhubNoTimeLoding;
    [PostNetWorking postNetWorkingStr:RequestUrlStr(payFor_order_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;

        if ([responseObject[@"code"] intValue]==200) {

            if ([_payType isEqualToString:@"wxpay"]) {

                PayReq* req             = [[PayReq alloc] init];
                req.openID              = [responseObject[@"datas"][@"Appparam"] objectForKey:@"appid"];
                req.partnerId           = [responseObject[@"datas"][@"Appparam"] objectForKey:@"partnerid"];
                req.prepayId            = [responseObject[@"datas"][@"Appparam"] objectForKey:@"prepayid"];
                req.nonceStr            = [responseObject[@"datas"][@"Appparam"] objectForKey:@"noncestr"];
                req.timeStamp           = [[responseObject[@"datas"][@"Appparam"] objectForKey:@"timestamp"] intValue];
                req.package             = [responseObject[@"datas"][@"Appparam"] objectForKey:@"packages"];
                req.sign                = [responseObject[@"datas"][@"Appparam"] objectForKey:@"sign"];

                [WXApi sendReq:req];

            }else {

                NSString *appScheme = @"AllFamily";

                [[AlipaySDK defaultService] payOrder:responseObject[@"datas"][@"pay_string"]  fromScheme:appScheme callback:^(NSDictionary *resultDic) {
                    NSLog(@"reslut = %@",resultDic);

                }];
            }
        } else {

            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }

    } failed:^(NSError *error) {
        SHuiMBHidleYes;
        SHuiMBhudTextNetError;
    }];

}


//微信支付完成通知
-(void)payWxResultOpt:(NSNotification *)notification
{
    PayResp *response=(PayResp*)notification.object;

    if (response.errCode == WXSuccess)
    {

        UIAlertView *alerte = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"支付成功了~~！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alerte show];

    }
    else
    {
        UIAlertView *alerte = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"支付失败了~~！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alerte show];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
   
        if (buttonIndex == 0) {
            
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
  
}
-(void)ZFBSuccess:(NSNotification *)notification {
    
    UIAlertView *alerte = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"支付成功了~~！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alerte show];
}

-(void)dealloc{
    
    //第一种方法.这里可以移除该控制器下的所有通知
    
    NSLog(@"移除了所有的通知");
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}


@end
